// 个人信息问卷逻辑处理文件

/**
 * 计算个人信息评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculatePersonalInfoAssessment(formData) {
  // 个人信息问卷主要是数据收集，不涉及评分计算
  // 但可以生成一些统计信息和完整性评估
  
  const completeness = calculateCompleteness(formData);
  const bmi = calculateBMI(formData);
  
  return {
    completeness: completeness,
    bmi: bmi,
    summary: generateSummary(formData, completeness, bmi),
    dataQuality: assessDataQuality(formData)
  };
}

/**
 * 计算信息完整度
 * @param {Object} formData - 表单数据
 * @returns {Object} 完整度信息
 */
function calculateCompleteness(formData) {
  // 个人信息字段已改为选填，不再有必填字段
  const requiredFields = [];
  const optionalFields = [
    'patientName', 'age', 'gender', 'phone',  // 个人信息字段改为可选
    'idCard', 'birthDate', 'email', 'address',
    'maritalStatus', 'education', 'occupation', 'retired',
    'height', 'weight', 'bloodType', 'allergies', 'medicalHistory', 'currentMedications',
    'emergencyContactName', 'emergencyContactRelation', 'emergencyContactPhone',
    'remarks'
  ];
  
  let requiredCount = 0;
  let optionalCount = 0;
  
  requiredFields.forEach(field => {
    if (formData[field] && formData[field] !== '') {
      requiredCount++;
    }
  });
  
  optionalFields.forEach(field => {
    if (formData[field] && formData[field] !== '') {
      optionalCount++;
    }
  });
  
  const requiredCompleteness = requiredFields.length > 0 ? (requiredCount / requiredFields.length) * 100 : 100;
  const optionalCompleteness = optionalFields.length > 0 ? (optionalCount / optionalFields.length) * 100 : 0;
  const totalCompleteness = (requiredFields.length + optionalFields.length) > 0 
    ? ((requiredCount + optionalCount) / (requiredFields.length + optionalFields.length)) * 100 
    : 0;
  
  return {
    required: {
      filled: requiredCount,
      total: requiredFields.length,
      percentage: requiredCompleteness.toFixed(1)
    },
    optional: {
      filled: optionalCount,
      total: optionalFields.length,
      percentage: optionalCompleteness.toFixed(1)
    },
    total: {
      filled: requiredCount + optionalCount,
      total: requiredFields.length + optionalFields.length,
      percentage: totalCompleteness.toFixed(1)
    }
  };
}

/**
 * 计算BMI指数
 * @param {Object} formData - 表单数据
 * @returns {Object} BMI信息
 */
function calculateBMI(formData) {
  const height = parseFloat(formData.height);
  const weight = parseFloat(formData.weight);
  
  if (!height || !weight || height <= 0 || weight <= 0) {
    return {
      value: null,
      category: '无法计算',
      description: '身高或体重信息不完整'
    };
  }
  
  const heightInMeters = height / 100;
  const bmi = weight / (heightInMeters * heightInMeters);
  
  let category = '';
  let description = '';
  
  if (bmi < 18.5) {
    category = '偏瘦';
    description = 'BMI < 18.5，建议适当增加营养';
  } else if (bmi < 24) {
    category = '正常';
    description = '18.5 ≤ BMI < 24，体重正常';
  } else if (bmi < 28) {
    category = '偏胖';
    description = '24 ≤ BMI < 28，建议控制饮食和增加运动';
  } else {
    category = '肥胖';
    description = 'BMI ≥ 28，建议咨询医生制定减重计划';
  }
  
  return {
    value: bmi.toFixed(2),
    category: category,
    description: description,
    height: height,
    weight: weight
  };
}

/**
 * 生成信息摘要
 * @param {Object} formData - 表单数据
 * @param {Object} completeness - 完整度信息
 * @param {Object} bmi - BMI信息
 * @returns {String} 摘要文本
 */
function generateSummary(formData, completeness, bmi) {
  let summary = `姓名：${formData.patientName || '未填写'}\n`;
  summary += `年龄：${formData.age || '未填写'}岁\n`;
  summary += `性别：${formData.gender === 'male' ? '男性' : formData.gender === 'female' ? '女性' : '其他'}\n`;
  summary += `联系电话：${formData.phone || '未填写'}\n`;
  
  if (formData.idCard) {
    summary += `身份证号：${formData.idCard}\n`;
  }
  
  if (bmi.value) {
    summary += `BMI指数：${bmi.value} (${bmi.category})\n`;
  }
  
  summary += `\n信息完整度：${completeness.total.percentage}%\n`;
  summary += `必填项完整度：${completeness.required.percentage}%\n`;
  summary += `可选项完整度：${completeness.optional.percentage}%\n`;
  
  return summary;
}

/**
 * 评估数据质量
 * @param {Object} formData - 表单数据
 * @returns {Object} 数据质量评估
 */
function assessDataQuality(formData) {
  const issues = [];
  const warnings = [];
  
  // 检查年龄合理性
  if (formData.age) {
    const age = parseInt(formData.age);
    if (age < 0 || age > 150) {
      issues.push('年龄超出合理范围');
    }
  }
  
  // 检查身高合理性
  if (formData.height) {
    const height = parseFloat(formData.height);
    if (height < 50 || height > 250) {
      issues.push('身高超出合理范围');
    }
  }
  
  // 检查体重合理性
  if (formData.weight) {
    const weight = parseFloat(formData.weight);
    if (weight < 20 || weight > 300) {
      issues.push('体重超出合理范围');
    }
  }
  
  // 检查身份证号格式（简单验证）
  if (formData.idCard) {
    const idCard = formData.idCard.replace(/\s/g, '');
    if (idCard.length !== 15 && idCard.length !== 18) {
      warnings.push('身份证号长度不符合标准格式');
    }
  }
  
  // 检查电话号码格式（简单验证）
  if (formData.phone) {
    const phone = formData.phone.replace(/\s|-/g, '');
    if (phone.length < 7 || phone.length > 15) {
      warnings.push('电话号码格式可能不正确');
    }
  }
  
  return {
    quality: issues.length === 0 ? '良好' : '需检查',
    issues: issues,
    warnings: warnings,
    hasIssues: issues.length > 0,
    hasWarnings: warnings.length > 0
  };
}

/**
 * 生成个人信息登记报告
 * @param {Object} assessmentResult - 评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 登记报告
 */
export function generatePersonalInfoReport(assessmentResult, formData) {
  return {
    basicInfo: {
      name: formData.patientName || '未填写',
      age: formData.age || '未填写',
      gender: formData.gender === 'male' ? '男' : formData.gender === 'female' ? '女' : '其他',
      phone: formData.phone || '未填写',
      idCard: formData.idCard || '未填写',
      email: formData.email || '未填写',
      address: formData.address || '未填写',
      birthDate: formData.birthDate || '未填写'
    },
    
    socialInfo: {
      maritalStatus: getMaritalStatusLabel(formData.maritalStatus),
      education: getEducationLabel(formData.education),
      occupation: formData.occupation || '未填写',
      retired: formData.retired === 'yes' ? '是' : formData.retired === 'no' ? '否' : '未填写'
    },
    
    healthInfo: {
      height: formData.height ? `${formData.height} cm` : '未填写',
      weight: formData.weight ? `${formData.weight} kg` : '未填写',
      bmi: assessmentResult.bmi,
      bloodType: formData.bloodType || '未填写',
      allergies: formData.allergies || '无',
      medicalHistory: formData.medicalHistory || '无',
      currentMedications: formData.currentMedications || '无'
    },
    
    contactInfo: {
      name: formData.emergencyContactName || '未填写',
      relation: formData.emergencyContactRelation || '未填写',
      phone: formData.emergencyContactPhone || '未填写'
    },
    
    completeness: assessmentResult.completeness,
    dataQuality: assessmentResult.dataQuality,
    summary: assessmentResult.summary,
    generateTime: new Date().toLocaleString('zh-CN')
  };
}

/**
 * 获取婚姻状况标签
 */
function getMaritalStatusLabel(value) {
  const map = {
    'single': '未婚',
    'married': '已婚',
    'divorced': '离异',
    'widowed': '丧偶',
    'other': '其他'
  };
  return map[value] || '未填写';
}

/**
 * 获取教育程度标签
 */
function getEducationLabel(value) {
  const map = {
    'illiterate': '文盲',
    'primary': '小学',
    'middle': '初中',
    'high': '高中/中专',
    'college': '大专',
    'university': '本科',
    'graduate': '研究生及以上'
  };
  return map[value] || '未填写';
}

/**
 * 验证个人信息表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果
 */
export function validatePersonalInfoForm(formData) {
  const errors = [];
  const warnings = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // 只验证如果填写了年龄，则必须在有效范围内
  if (formData.age !== null && formData.age !== undefined && formData.age !== '') {
    const age = parseInt(formData.age);
    if (isNaN(age) || age < 0 || age > 150) {
      errors.push('年龄应在0-150岁之间');
    }
  }
  
  // 数据合理性验证
  if (formData.height && (formData.height < 50 || formData.height > 250)) {
    warnings.push('身高应在50-250cm之间');
  }
  
  if (formData.weight && (formData.weight < 20 || formData.weight > 300)) {
    warnings.push('体重应在20-300kg之间');
  }
  
  // 身份证号格式验证
  if (formData.idCard) {
    const idCard = formData.idCard.replace(/\s/g, '');
    if (idCard.length !== 15 && idCard.length !== 18) {
      warnings.push('身份证号应为15位或18位');
    }
  }
  
  // 电话号码格式验证
  if (formData.phone) {
    const phone = formData.phone.replace(/\s|-/g, '');
    if (phone.length < 7 || phone.length > 15) {
      warnings.push('电话号码格式可能不正确');
    }
  }
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    hasWarnings: warnings.length > 0
  };
}

export default {
  calculatePersonalInfoAssessment,
  generatePersonalInfoReport,
  validatePersonalInfoForm
};

